from django.db.models import Q
from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView,Response
from .sers import *


class Login(APIView):
    def post(self, request):
        # 获取数据
        username = request.data.get('username')
        password = request.data.get('password')
        # 获取满足username和password相同的对象
        user_obj = UserModel.objects.filter(username=username, password=password).first()
        # 判断user_obj
        if user_obj:
            # 返回登录成功给前端返回一个权限
            return Response({'msg': '登录成功', 'code': 200, 'admin': user_obj.admin, 'user_id': user_obj.id})

        return Response({'msg': '登录失败', 'code': 400})


class OrderApi(APIView):
    def post(self, request):
        # 获取数据
        product = request.data.get('product')
        phone = request.data.get('phone')
        # 过滤
        ding_obj = OrderModel.objects.filter(Q(phone=phone) & Q(product_id=product)).first()
        if ding_obj:
            # 判断ding_obj值
            return Response({'msg': '订单已存在', 'code': 400})
        else:
            # 接受所有参数
            ser = OrderModelSerializers(data=request.data)
            if ser.is_valid():
                # 校验数据
                ser.save()
                return Response({'msg': '下单成功', 'code': 200})
            else:
                return Response({'error': ser.errors})
    def get(self,request):
        # 获取所有订单
        user_id = request.query_params.get('user_id')
        user_obj = OrderModel.objects.filter(user_id=user_id)
        list = ShowOrderModelSerializers(user_obj,many=True)
        return Response(list.data)

class ProductApi(APIView):
    def get(self, request):
        # 获取所有商品
        list = Products.objects.all()
        ser = ProductSerializers(list, many=True)
        return Response(ser.data)
